#!/bin/bash -e

function usage { cat <<EOF
USAGE: $0 output-dir aws-region internal-tld k8s-service-ip
  example: $0 .cfssl us-west-1 test.k8s 10.3.0.1
EOF

  exit 1
}

OUTDIR=$1
[ -z "$OUTDIR" ] && usage

AWS_REGION=$2
[ -z "$AWS_REGION" ] && usage

INTERNAL_TLD=$3
[ -z "$INTERNAL_TLD" ] && usage

K8S_SERVICE_IP=$4
[ -z "$K8S_SERVICE_IP" ] && usage

set -o nounset
set -o pipefail

function ca-csr {
  cat <<EOF
{
  "CN": "CA",
  "key": { "algo": "rsa", "size": 2048 },
  "names": [{ "C": "US", "L": "San Francisco", "O": "Kubernetes", "ST": "California" }]
}
EOF
}

function ca-config {
  cat <<EOF
{
  "signing": {
    "default": { "expiry": "43800h" },
    "profiles": {
      "server": {
        "expiry": "43800h",
        "usages": [ "signing", "key encipherment", "server auth" ]
      },
      "client": {
        "expiry": "43800h",
        "usages": [ "signing", "key encipherment", "client auth" ]
      },
      "client-server": {
        "expiry": "43800h",
        "usages": [ "signing", "key encipherment", "server auth", "client auth" ]
      }
    }
  }
}
EOF
}

function csr {
  cat <<EOF
{"CN":"$1","hosts":[""],"key":{"algo":"rsa","size":2048}}
EOF
}

DNS1="kubernetes"
DNS2="kubernetes.default"
DNS3="kubernetes.default.svc"
DNS4="kubernetes.default.svc.cluster.local"
DEFAULT_HOSTS="$DNS1,$DNS2,$DNS3,$DNS4,127.0.0.1"

function _chmod {
  CN=$1
  chmod 0644 $CN.pem ${CN}-key.pem
}

function generate {
  CN=$1
  PROFILE=$2
  HOSTS=$3

  echo "$(csr $CN)" \
    | cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json \
      -profile=$PROFILE \
      -hostname="$HOSTS" - \
    | cfssljson -bare $CN

  _chmod $CN

  # tar -cf $CN.tar ca.pem $CN.pem ${CN}-key.pem
}

mkdir -p $OUTDIR && cd $OUTDIR
echo "$(ca-csr)" >ca-csr.json
echo "$(ca-config)" >ca-config.json

# generate ca
cfssl gencert -initca ca-csr.json | cfssljson -bare ca -
_chmod ca

# generate keys and certs
generate k8s-admin client-server "${DEFAULT_HOSTS},*.*.compute.internal,*.ec2.internal"
generate k8s-apiserver client-server "${DEFAULT_HOSTS},${K8S_SERVICE_IP},master.${INTERNAL_TLD},*.${AWS_REGION}.elb.amazonaws.com"
generate k8s-etcd client-server "etcd.${INTERNAL_TLD},etcd1.${INTERNAL_TLD},etcd2.${INTERNAL_TLD},etcd3.${INTERNAL_TLD}"
generate k8s-worker client "${DEFAULT_HOSTS},*.*.compute.internal,*.ec2.internal"

# TODO: fix cert provisioning hacks
# tar -rf k8s-apiserver.tar k8s-etcd.pem k8s-etcd-key.pem
# tar -rf k8s-worker.tar ca.pem
# bzip2 k8s-apiserver.tar
# bzip2 k8s-worker.tar
